package com.gsk.europepharma.salesReport.struts.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;

import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRSectoDAO;

/**
 * Gestion des donnees pour l'affichage du tableau contenant la liste des medecins.
 */
public class DataGridDoctors extends Action {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// Variables de session
		HttpSession sessionObject = request.getSession();
		Integer cs_network = (Integer) sessionObject.getAttribute("cs_network");
		// Fin de session
		
		String idGeog = request.getParameter("idGeog");
		Integer idGeogInteger = Integer.parseInt(idGeog);
		String nivGeog = request.getParameter("nivGeog");
		
		String cs_division_string = request.getParameter("cs_division");
		Integer cs_division = Integer.parseInt(cs_division_string);
		String periodeActivite = request.getParameter("periodeActivite");
		String specialite = request.getParameter("specialite");
		String segments = request.getParameter("segments");
		
//		String segments = request.getParameter("segments");
//		String tabSegments[] = segments.split(" ");
//		List<String> segmentsListe = new ArrayList<String>();
//		if (tabSegments != null && tabSegments.length != 0) {
//			for (String segm : tabSegments) {
//				segmentsListe.add(segm);
//			}
//		}
		
		// Nombre de medecins par page 
		int nombreMedecinsParPage = Integer.parseInt(request.getParameter("itemsParPage"));
		// Indice de debut 
		String start = request.getParameter("start");
		
		int nombreTotalMedecins = 0;
		
		// Requete pour determiner le nombre total de medecins 
		tbSpBoSRSectoDAO salesDAO = new tbSpBoSRSectoDAO();
		Session session = salesDAO.getSession();
		Query req = null;
		String strReq = salesDAO.QUERY_QUERY_LISTE_MEDECINS_COUNT; 
		req = session.getNamedQuery(strReq);
		req.setString("fieldFiltername", "X");
		req.setString("valueFiltername", "");
		req.setString("fieldFilterfirstname", "X");
		req.setString("valueFilterfirstname", "");
		req.setString("fieldFilterzipCode", "X");
		req.setString("valueFilterzipCode", "");
		req.setString("fieldFiltercity", "X");
		req.setString("valueFiltercity", "");
		req.setString("fieldFilterspe", "X");
		req.setString("valueFilterspe", "");
		
		// TODO: 
//		req.setString("fieldFiltercible", "X");
//		req.setString("valueFiltercible", "");
//		req.setString("fieldFilternbCalls", "X");
//		req.setString("valueFilternbCalls", "");
//		req.setString("fieldFilterdernVis", "X");
//		req.setString("valueFilterdernVis", "");
//		req.setString("fieldFilterproVis", "X");
//		req.setString("valueFilterproVis", "");
		
		req.setString("fieldFilternofilter", "X");
		if (request.getParameter("filter") != null) {
			String tab[] = request.getParameter("filter").split("\"");
			int length = tab.length;
			int i = 7;
			int j = 0;
			int nbFilters = length / 12;
			while (j < nbFilters) {
				String value = tab[i];
				i += 4;
				String property = tab[i];
				i += 8;
				req.setString("fieldFilter" + property, property);
				req.setString("valueFilter" + property, value);
				j++;
			}
		} else {
			req.setString("fieldFilternofilter", "nofilter");
		}
		req.setInteger("cs_network", cs_network);
		req.setInteger("idGeog", idGeogInteger);
		req.setString("nivGeog", nivGeog);	
		ArrayList result = new ArrayList(req.list());
		nombreTotalMedecins = Integer.parseInt(result.get(0).toString());
		// Mise en session du nombre de medecins 
		sessionObject.setAttribute("nombreMedecins", result.get(0).toString());
		
		// Calcul des indices min et max 
		int beginIndex = Integer.parseInt(start);
		int endIndex = Integer.parseInt(start) + nombreMedecinsParPage;
		if (endIndex > nombreTotalMedecins) {
			endIndex = nombreTotalMedecins;
		}
		
		// Requete 
		salesDAO = new tbSpBoSRSectoDAO();
		session = salesDAO.getSession();
		req = null;
		strReq = salesDAO.QUERY_QUERY_LISTE_MEDECINS; 
		req = session.getNamedQuery(strReq); 
		req.setInteger("cs_network",	cs_network);
		req.setInteger("idGeog",		idGeogInteger);
		req.setString("nivGeog",		nivGeog);	
		req.setInteger("min",			beginIndex);
		req.setInteger("max",			endIndex);
		if (request.getParameter("sort") != null) {
			String tab[] = request.getParameter("sort").split("\"");
			String property = tab[3];
			String order = tab[7];
			req.setString("fieldOrder", property);
			req.setString("ascDescOrder", order);
		} else {
			req.setString("fieldOrder", "name");
			req.setString("ascDescOrder", "ASC");
		}
		req.setString("fieldFiltername", "X");
		req.setString("valueFiltername", "");
		req.setString("fieldFilterfirstname", "X");
		req.setString("valueFilterfirstname", "");
		req.setString("fieldFilterzipCode", "X");
		req.setString("valueFilterzipCode", "");
		req.setString("fieldFiltercity", "X");
		req.setString("valueFiltercity", "");
		req.setString("fieldFilterspe", "X");
		req.setString("valueFilterspe", "");
		req.setString("fieldFilternofilter", "X");
		
		// TODO:
//		req.setString("fieldFiltercible", "X");
//		req.setString("valueFiltercible", "");
//		req.setString("fieldFilternbCalls", "X");
//		req.setString("valueFilternbCalls", "");
//		req.setString("fieldFilterdernVis", "X");
//		req.setString("valueFilterdernVis", "");
//		req.setString("fieldFilterproVis", "X");
//		req.setString("valueFilterproVis", "");
		
		if (request.getParameter("filter") != null) {
			String tab[] = request.getParameter("filter").split("\"");
			int length = tab.length;
			int i = 7;
			int j = 0;
			int nbFilters = length / 12;
			while (j < nbFilters) {
				String value = tab[i];
				i += 4;
				String property = tab[i];
				i += 8;
				req.setString("fieldFilter" + property, property);
				req.setString("valueFilter" + property, value);
				j++;
			}
		} else {
			req.setString("fieldFilternofilter", "nofilter");
		}
		
		result = new ArrayList(req.list());

		// Construction de la liste des medecins 
		JSONArray medecins = new JSONArray();
		int i = 0;
		Iterator iter = result.iterator();
		while (iter.hasNext()) {
			Object[] infosMedecin = (Object[]) iter.next();
			JSONObject medecin = new JSONObject();
			medecin.put("id",			i);
			medecin.put("name",			infosMedecin[4].toString());
			medecin.put("firstname",	infosMedecin[5].toString());
			medecin.put("zipCode",		infosMedecin[7].toString());
			medecin.put("city",			infosMedecin[8].toString());
			medecin.put("spe",			infosMedecin[9].toString());
			medecin.put("subtype",		infosMedecin[11].toString());
			
			if (i % 2 == 0) {
				medecin.put("cible", "B"); // TODO:
			} else {
				medecin.put("cible", "A"); // TODO:
			}
			medecin.put("nbCalls", i + " / " + i); // TODO:
			medecin.put("dernVis", "02/10/" + i); // TODO:
			medecin.put("proVis", "01/01/" + i); // TODO:
			
			i++;
			// Ajout d'un médecin 
			medecins.add(medecin);
		}
		
		// Données JSON envoyées 
		HashMap hm = new HashMap();
		JSONObject res = new JSONObject();
		res.put("total",	nombreTotalMedecins);
		res.put("data",		medecins);
		res.put("id",		"gridDoctorsStore");
		hm.put("result",	res);
		
		// Envoie
		JSONObject json = JSONObject.fromObject(hm);
		response.addHeader("Content-Type", "application/json");
        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
        response.getOutputStream().flush();
		return null;
		
	}

}
